package org.toools.gwt.wmc.server.account;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.util.Collection;
import org.toools.gwt.wmc.client.account.AccountService;
import org.toools.gwt.wmc.client.exceptions.dao.EmailExistsException;
import org.toools.gwt.wmc.client.exceptions.dao.WrongLoginException;
import org.toools.gwt.wmc.server.dao.IAccountDAO;
import org.toools.gwt.wmc.jpa.Account;
import org.toools.gwt.wmc.server.WMCSession;

public class AccountServiceImpl extends RemoteServiceServlet implements AccountService {

    private IAccountDAO accountdao;

    /** Account DAO **/
    public void setAccountdao( IAccountDAO dao ) {
        this.accountdao = dao;
    }
    public IAccountDAO getAccountdao() {
		return accountdao;
	}
    
    public Integer login(String email, String pwd) throws WrongLoginException {
        Account ac = accountdao.Login(email, pwd);
        if( ac == null )
            throw new WrongLoginException();
        WMCSession.setAccount( getThreadLocalRequest(), ac);
        return ac.getId();
    }
    
    public Boolean logout() {
        WMCSession.removeAccount( getThreadLocalRequest() );
        return true;
    }

    public Integer register(String email, String pwd) throws EmailExistsException {
        Account a = new Account();
        a.setEmail( email );
        a.setPassword( pwd );
        if( accountdao.getAccounts().size() == 0 )
            a.setAdmin( true );
        return accountdao.Register( a );
    }
    
    public Account getAccountByID(Integer ID) {
        if( !WMCSession.isAdmin( getThreadLocalRequest() ) || !WMCSession.getAccountID( getThreadLocalRequest() ).equals( ID ) )
            return null;

        return accountdao.getAccountByID( ID );
    }

    public Collection<Account> getAccounts() {
        if( WMCSession.isAdmin( getThreadLocalRequest() ) )
            return accountdao.getAccounts();

        return null;
    }

    public Boolean update(Account a) {
        if( !WMCSession.isAdmin( getThreadLocalRequest() ) || !WMCSession.getAccountID( getThreadLocalRequest() ).equals( a.getId() ) )
            return false;
        //can only set admin, if:
        // logged in account is admin
        a.setAdmin( a.isAdmin() && WMCSession.isAdmin( getThreadLocalRequest() ) );
        return accountdao.update( a );
    }

    public Boolean delete(Account a) {
        if( !WMCSession.isAdmin( getThreadLocalRequest() ) || !WMCSession.getAccountID( getThreadLocalRequest() ).equals( a.getId() ) )
            return false;
        
        return accountdao.delete( a );
    }
}